package com.tchhy.mvplibrary.rx

import android.app.Activity
import android.content.Context
import android.content.Intent
import com.google.gson.Gson
import com.tchhy.basemodule.basedata.TokenHelper
import com.tchhy.basemodule.basedata.UserInfoHelper
import com.tchhy.basemodule.utils.MedicineUsageNoticeClearUtil
import com.tchhy.basemodule.utils.SystemUtils
import com.tchhy.mvplibrary.BuildConfig
import com.tchhy.mvplibrary.presenter.view.BaseView
import com.tchhy.provider.data.common.BaseResp
import com.tchhy.provider.data.common.EmptyResp
import com.tchhy.provider.event.UpdataIdEvent
import com.tchhy.provider.rx.RxErrorHandle
import com.tchhy.toast.ToastUtils
import com.trello.rxlifecycle2.LifecycleProvider
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import retrofit2.HttpException
import java.lang.Exception

/**
 * Describe: RxJava线程戏相关
 *
 */
open class DefaultObserverNoToast<T>(
    var context: Activity,
    val lifecycleProvider: LifecycleProvider<*>,
    val view: BaseView?,
    private val onSuccess: (T) -> Unit
) : Observer<BaseResp<T>> {

    open fun onErrorMessage(errorMessage: String) {
        view?.dismissLoading()
        view?.onError(errorMessage)
    }

    open fun onErrorMessage(code: Int,errorMessage: String) {
        view?.onErrorMessage(code,errorMessage)
        view?.dismissLoading()
    }

    open fun onOtherCode(code: Int, data: T?) {

    }

    override fun onNext(t: BaseResp<T>) {
        view?.dismissLoading()
        if (t.status == 0) {
            if (t.data != null) {
                onSuccess.invoke(t.data!!)
            } else {
                onDataNull()
            }
        } else {
            onOtherCode(t.status, t.data)
            onErrorMessage(t.status,t.message)
        }
    }

    open fun onDataNull() {
        view?.onDataNull()
    }


    override fun onComplete() {
    }

    override fun onSubscribe(d: Disposable) {
        view?.showLoading()
    }

    override fun onError(e: Throwable) {
        view?.dismissLoading()
        if (e is HttpException) {
            val errorBody = e.response()?.errorBody()?.string()
            try {
                val emptyResponse = Gson().fromJson(errorBody, EmptyResp::class.java)
                when (emptyResponse.status) {
                    ServiceCodeEnum.CODE_ACCESS_TOKEN_EXPIRED,
                    ServiceCodeEnum.CODE_ACCESS_TOKEN_VALIDATE_ERROR,
                    ServiceCodeEnum.CODE_ACCESS_REFRESH_TOKEN_VALIDATE_ERROR -> {
                        jumpToLoginActivity()
                    }
                    ServiceCodeEnum.CODE_LIMIT -> {
                        jumpToAbnormalActivity()
                    }
                }
                if (emptyResponse.status == ServiceCodeEnum.CODE_REMOVED_FAMILY) {
                    if (!emptyResponse.message.isNullOrEmpty()) {
                        val msgs = emptyResponse.message.split("&")
                        if (msgs.size == 2) {
                            ToastUtils.show(msgs[0])
                            EventBus.getDefault().post(UpdataIdEvent(msgs[1]))
                        } else {
                            ToastUtils.show(emptyResponse.message + "")
                        }
                    }
                } else {
                    if (BuildConfig.DEBUG) {//是否是正式服务器
                        ToastUtils.show("接口异常：响应码：" + e.code() + "\n原因：" + emptyResponse.message)
                    } else {
                        ToastUtils.show(emptyResponse.message + "")
                    }
                }
                view?.onError(emptyResponse.message)
            } catch (e: Exception) {
                ToastUtils.show("网络连接不稳定，请稍后再试")
                view?.onError(errorBody ?: "")
            }
        } else {
            ToastUtils.show("网络连接不稳定，请稍后再试")
            //ToastUtils.show("服务器错误：\n原因：" + RxErrorHandle(e).error())
            view?.onError(RxErrorHandle(e).error())
        }

    }

    private fun jumpToLoginActivity() {
        val clz = Class.forName("com.tchhy.tcjk.ui.login.activity.LoginNewActivity")
        val intent = Intent(context, clz)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        UserInfoHelper.clearAccountInfo(context)
        TokenHelper.clearAuthorization(context)
        MedicineUsageNoticeClearUtil.cancelAllTask()
        context.startActivity(intent)
    }

    private fun jumpToAbnormalActivity() {
        val clz = Class.forName("com.tchhy.tcjk.ui.abnormal.AbnormalActivity")
        val intent = Intent(context, clz)
        intent.putExtra("accessName", SystemUtils.getTopActivity(context))
        context.startActivity(intent)
    }
}